package cn.harry.cabinet.view.dialog

import android.app.Dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.RadioGroup
import android.widget.TextView
import androidx.fragment.app.DialogFragment
import cn.harry.cabinet.R
import cn.harry.cabinet.model.entity.User
import cn.harry.cabinet.model.enums.Gender
import cn.harry.cabinet.model.enums.UserStatus

class UserFormDialogFragment(
    private val user: User? = null, // null表示添加，非null表示编辑
    private val onUserSaved: (User) -> Unit
) : DialogFragment() {

    private lateinit var dialogTitle: TextView
    private lateinit var nameEditText: EditText
    private lateinit var employeeIdEditText: EditText
    private lateinit var phoneNumberEditText: EditText
    private lateinit var positionEditText: EditText
    private lateinit var featureCodeEditText: EditText
    private lateinit var passwordEditText: EditText
    private lateinit var genderRadioGroup: RadioGroup
    private lateinit var statusRadioGroup: RadioGroup
    private var isPasswordVisible = false

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.dialog_user_form, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        initViews(view)
        setupListeners()
        
        // 如果是编辑模式，填充现有数据
        user?.let { fillUserData(it) }
    }

    private fun initViews(view: View) {
        dialogTitle = view.findViewById(R.id.dialogTitle)
        nameEditText = view.findViewById(R.id.nameEditText)
        employeeIdEditText = view.findViewById(R.id.employeeIdEditText)
        phoneNumberEditText = view.findViewById(R.id.phoneNumberEditText)
        positionEditText = view.findViewById(R.id.positionEditText)
        featureCodeEditText = view.findViewById(R.id.featureCodeEditText)
        passwordEditText = view.findViewById(R.id.passwordEditText)
        genderRadioGroup = view.findViewById(R.id.genderRadioGroup)
        statusRadioGroup = view.findViewById(R.id.statusRadioGroup)
        
        // 根据是否有用户数据来设置标题
        dialogTitle.text = if (user == null) "添加新用户" else "编辑用户"
    }

    private fun setupListeners() {
        view?.findViewById<View>(R.id.confirmButton)?.setOnClickListener {
            if (validateInputs()) {
                val user = createUserFromInputs()
                onUserSaved(user)
                dismiss()
            }
        }

        view?.findViewById<View>(R.id.cancelButton)?.setOnClickListener {
            dismiss()
        }

    }

    private fun fillUserData(user: User) {
        nameEditText.setText(user.name)
        employeeIdEditText.setText(user.employeeId)
        phoneNumberEditText.setText(user.phoneNumber)
        positionEditText.setText(user.position)
        featureCodeEditText.setText(user.featureCode)
        passwordEditText.setText(user.password)

        // 设置性别选择
        when (user.gender) {
            Gender.MALE -> genderRadioGroup.check(R.id.maleRadioButton)
            Gender.FEMALE -> genderRadioGroup.check(R.id.femaleRadioButton)
        }

        // 设置状态选择
        when (user.status) {
            UserStatus.ENABLED -> statusRadioGroup.check(R.id.enabledRadioButton)
            UserStatus.DISABLED -> statusRadioGroup.check(R.id.disabledRadioButton)
        }
    }

    private fun validateInputs(): Boolean {
        var isValid = true

        // 验证必填字段
        if (nameEditText.text.toString().trim().isEmpty()) {
            nameEditText.error = "请输入姓名"
            isValid = false
        }

        if (employeeIdEditText.text.toString().trim().isEmpty()) {
            employeeIdEditText.error = "请输入工号"
            isValid = false
        }

        if (phoneNumberEditText.text.toString().trim().isEmpty()) {
            phoneNumberEditText.error = "请输入手机号"
            isValid = false
        }

        if (positionEditText.text.toString().trim().isEmpty()) {
            positionEditText.error = "请输入岗位"
            isValid = false
        }

        return isValid
    }

    private fun createUserFromInputs(): User {
        val name = nameEditText.text.toString().trim()
        val employeeId = employeeIdEditText.text.toString().trim()
        val phoneNumber = phoneNumberEditText.text.toString().trim()
        val position = positionEditText.text.toString().trim()
        val featureCode = featureCodeEditText.text.toString().trim()
        val password = passwordEditText.text.toString().trim()

        // 获取性别选择
        val gender = when (genderRadioGroup.checkedRadioButtonId) {
            R.id.maleRadioButton -> Gender.MALE
            R.id.femaleRadioButton -> Gender.FEMALE
            else -> Gender.MALE
        }

        // 获取状态选择
        val status = when (statusRadioGroup.checkedRadioButtonId) {
            R.id.enabledRadioButton -> UserStatus.ENABLED
            R.id.disabledRadioButton -> UserStatus.DISABLED
            else -> UserStatus.ENABLED
        }

        return if (user != null) {
            // 编辑模式：保留原有ID和时间戳
            user.copy(
                name = name,
                employeeId = employeeId,
                phoneNumber = phoneNumber,
                position = position,
                gender = gender,
                status = status,
                featureCode = featureCode,
                password = password,
                updateTime = java.util.Date()
            )
        } else {
            // 添加模式：创建新用户
            User(
                employeeId = employeeId,
                name = name,
                phoneNumber = phoneNumber,
                position = position,
                gender = gender,
                status = status,
                featureCode = featureCode,
                password = password,
                createTime = java.util.Date(),
                updateTime = java.util.Date()
            )
        }
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val dialog = super.onCreateDialog(savedInstanceState)
        val title = if (user != null) "编辑用户信息" else "添加新用户"
        dialog.setTitle(title)
        return dialog
    }
} 